package com.bwie.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bwie.config.RedisConfig;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.Result;
import com.bwie.pojo.po.UserPo;
import com.bwie.service.UserService;
import com.bwie.utils.SendMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * @className: UserServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 杜林涛
 * @date: 2025/6/11 10:05
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    HttpServletRequest request;
    @Override
    public Result sendCode(String phone) {
        JedisPool jedisPool = RedisConfig.redisConn();
        Jedis jedis = jedisPool.getResource();
        //生成随机4位数字验证码（首位禁止为0）
        Random random = new Random();
        int i = random.nextInt(9999 - 1000 + 1) + 1000;
        //通过工具类给手机发送验证码
        jedis.setex("send" + phone, 60, "" + i);
        String s1 = SendMsgUtil.sendSms(String.valueOf(i), phone);
        //将验证码存到redis存2分钟
        jedis.setex("code" + phone, 120, String.valueOf(i));
        //防恶意请求：Redis记录最近发送时间戳，1分钟内重复请求直接拦截
        //发送短信的同时倒计时存到redis
        return Result.success(s1);
    }

    @Override
    public Result uLogin(String phone, String code) {
        //判断手机号和验证码不为空
        if(phone==null){
            return Result.error("手机号不能为空");
        }
        if(code==null){
            return Result.error("验证码不能为空");
        }
        //手机号正则效验
        if(phone.matches("^1[3-9]\\d{9}$")){
            return Result.error("手机号格式不正确");
        }
        //获取验证码
        JedisPool jedisPool = RedisConfig.redisConn();
        Jedis jedis = jedisPool.getResource();
        String s = jedis.get("send" + code);
        if(ObjectUtil.isNull(s)){
            return Result.error("验证码不正确");
        }
        UserPo u=userMapper.uLogin(phone);
        if(ObjectUtil.isNull(u)){
            return Result.error("手机号不正确");
        }
        return Result.success("登录成功");
    }
}
